package com.kyxx.topics.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseActivity2;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.bean.ArticleBean;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.SizeUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class FavoriteActivity extends BaseActivity {
    private SwipeMenuListView smlv;
    private List<ArticleBean> articleBeanList = new ArrayList<>();
    ZhuanTiAdapter zhuanTiAdapter;
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private int pageSize = 1;
    private int countSize = 10;
    private String sid;
    private String title;
    private String demo;
    private String imageUrl;
    private int lastVisiblePosition;
    private SettingUtils settingUtils = new SettingUtils();

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_favorite);
        BaseApp.getInstance().addActivity(this);
    }

    @Override
    protected void loadTopBar(String title) {
        super.loadTopBar(title);
        top_bar_tv_left.setVisibility(View.GONE);
        top_bar_iv_left.setVisibility(View.VISIBLE);
        top_bar_tv_right.setVisibility(View.GONE);
        top_bar_iv_right.setVisibility(View.GONE);
        top_bar_iv_left.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_right));
        top_bar_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void findViewById() {
        loadTopBar("收藏");
        smlv = (SwipeMenuListView) findViewById(R.id.smlv);
//        smlv.setMenuCreator(creator);
//        smlv.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        smlv.setFocusable(false);
        rl_progress = (RelativeLayout) findViewById(R.id.rl_progress);
        avi = (ProgressBar) findViewById(R.id.avi);
        ll_reload = (LinearLayout) findViewById(R.id.ll_reload);
        ll_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initList(Constants.INITDATA, pageSize, countSize);
            }
        });
    }

    @Override
    protected void setListener() {
        smlv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        cancelFav(position);
                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });
        smlv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
                new AlertDialog.Builder(FavoriteActivity.this).setItems(new String[]{"取消收藏"}, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
                                cancelFav(i);
                                break;
                        }
                    }
                }).setNegativeButton("取消", null).show();
                return true;
            }
        });
        smlv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == smlv.getLastVisiblePosition())
                    return;
                lastVisiblePosition = smlv.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + smlv.getCount());
                if (lastVisiblePosition == smlv.getCount() - 2 && smlv.getCount() >= countSize) {
                    pageSize++;
                    initList(Constants.LOADMORE, pageSize, countSize);
                }

            }
        });

        smlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!TextUtils.isEmpty(articleBeanList.get(i).getVideo())) {
                    Intent intent = new Intent(context, DetailVideoActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    intent.putExtra("imageUrl", UrlUtils.BASEHTTP + articleBeanList.get(i).getImgurl().getPath());
                    intent.putExtra("videoUrl", articleBeanList.get(i).getVideo());
                    intent.putExtra("fav_position", i);
                    startActivityForResult(intent, 0);
                    return;
                }
                if (articleBeanList.get(i).getType() == 4) {
                    Intent intent = new Intent(context, DetailQuanActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    intent.putExtra("fav_position", i);
                    startActivityForResult(intent, 0);
                } else if (articleBeanList.get(i).getType() == 5) {
                    Intent intent = new Intent(context, DetailAdvertiseActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    intent.putExtra("fav_position", i);
                    startActivityForResult(intent, 0);
                } else {
                    Intent intent = new Intent(context, DetailActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    intent.putExtra("fav_position", i);
                    startActivityForResult(intent, 0);
                }
                addBrowseLog(articleBeanList.get(i).getId());
            }
        });
    }

    @Override
    protected void processLogic() {
        zhuanTiAdapter = new ZhuanTiAdapter();
        smlv.setAdapter(zhuanTiAdapter);
        initList(Constants.INITDATA, pageSize, countSize);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case Constants.CANCEL_FAV:
                if (articleBeanList != null) {
                    articleBeanList.remove(data.getIntExtra("fav_position", 0));
                    zhuanTiAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    class ZhuanTiAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return articleBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return articleBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(context, R.layout.item_zhuanti, null);
                holder.iv_zhuanti = (ImageView) view.findViewById(R.id.iv_zhuanti);
                holder.tv_title = (TextView) view.findViewById(R.id.tv_title);
                holder.tv_day = (TextView) view.findViewById(R.id.tv_day);
                holder.iv_focus = (ImageView) view.findViewById(R.id.iv_focus);
                holder.tv_num = (TextView) view.findViewById(R.id.tv_num);
                holder.tv_type = (TextView) view.findViewById(R.id.tv_type);
                holder.tv_read_num = (TextView) view.findViewById(R.id.tv_read_num);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            if (articleBeanList.get(i).getImgurl() != null) {
                imageLoader.displayImage(UrlUtils.BASEHTTP + articleBeanList.get(i).getImgurl().getPath(), holder.iv_zhuanti, options);
            } else {
                imageLoader.displayImage("", holder.iv_zhuanti, options);
            }
            switch (settingUtils.getZiTiDaXiao()) {
                case 0:
                    holder.tv_title.setTextSize(13);
                    break;
                case 1:
                    holder.tv_title.setTextSize(17);
                    break;
                case 2:
                    holder.tv_title.setTextSize(21);
                    break;
            }
            if (articleBeanList.get(i).getType() == 4) {
                holder.tv_type.setText("优惠券");
                holder.tv_type.setVisibility(View.VISIBLE);
            } else if (articleBeanList.get(i).getType() == 5) {
                holder.tv_type.setText("广告");
                holder.tv_type.setVisibility(View.VISIBLE);
            } else {
                holder.tv_type.setText("");
                holder.tv_type.setVisibility(View.GONE);
            }
            holder.tv_title.setText(articleBeanList.get(i).getTitle());
            holder.tv_day.setText(TimeUtils.milliseconds2String(Long.valueOf(articleBeanList.get(i).getCreate_time()) * 1000, new SimpleDateFormat("MM-dd HH:mm")));
            holder.tv_num.setText(articleBeanList.get(i).getComment());
            holder.tv_read_num.setText(StringUtil.numberFormat(articleBeanList.get(i).getView()));
            return view;
        }
    }

    class ViewHolder {
        private ImageView iv_zhuanti;
        private TextView tv_title;
        private TextView tv_day;
        private ImageView iv_focus;
        private TextView tv_num;
        private TextView tv_type;
        private TextView tv_read_num;
    }

    private void initList(final int type, int page, int count) {
        String url = UrlUtils.Bmarklist + "&uid=" + BaseApp.getModel().getId() + "&p=" + page + "&rows=" + count;
        String cacheKey = "speclist&uid=" + BaseApp.getModel().getId() + "&p=" + page + "&rows=" + count;
        OkGoRequest.get(url, FavoriteActivity.this, cacheKey, CacheMode.REQUEST_FAILED_READ_CACHE, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                switch (type) {
                    case Constants.INITDATA:
                        rl_progress.setVisibility(View.VISIBLE);
                        avi.setVisibility(View.VISIBLE);
                        ll_reload.setVisibility(View.GONE);
                        break;
                    default:
                        rl_progress.setVisibility(View.GONE);
                        break;

                }

            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                switch (type) {
                    case Constants.INITDATA:
                        rl_progress.setVisibility(View.VISIBLE);
                        avi.setVisibility(View.GONE);
                        ll_reload.setVisibility(View.VISIBLE);
                        break;
                    default:
                        rl_progress.setVisibility(View.GONE);
                        break;
                }

            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                rl_progress.setVisibility(View.GONE);
                try {
                    JSONObject result = new JSONObject(s);
                    switch (type) {
                        case Constants.INITDATA:
                            articleBeanList = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                            zhuanTiAdapter = new ZhuanTiAdapter();
                            smlv.setAdapter(zhuanTiAdapter);
                            break;
                        case Constants.LOADMORE:
                            articleBeanList.addAll(JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class));
                            zhuanTiAdapter.notifyDataSetChanged();
                            break;
                        case Constants.REFRESH:
                            articleBeanList = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                            zhuanTiAdapter = new ZhuanTiAdapter();
                            smlv.setAdapter(zhuanTiAdapter);
                            break;
                    }
                    lastVisiblePosition = smlv.getLastVisiblePosition();
                    if (articleBeanList==null||articleBeanList.size() == 0) {
                        rl_progress.setVisibility(View.VISIBLE);
                        findViewById(R.id.ll_no).setVisibility(View.VISIBLE);
                        avi.setVisibility(View.GONE);
                        ll_reload.setVisibility(View.GONE);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    rl_progress.setVisibility(View.VISIBLE);
                    findViewById(R.id.ll_no).setVisibility(View.VISIBLE);
                    avi.setVisibility(View.GONE);
                    ll_reload.setVisibility(View.GONE);
                }
            }
        });
    }

    private void addBrowseLog(String id) {
        if (TextUtils.isEmpty(BaseApp.getModel().getId()))
            return;
        HttpParams params = new HttpParams();
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        jsonObject.put("news_id", id);
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.addBrowseLog, FavoriteActivity.this, "addBrowseLog", CacheMode.NO_CACHE, params, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

            }
        });
    }

    SwipeMenuCreator creator = new SwipeMenuCreator() {

        @Override
        public void create(SwipeMenu menu) {
            // create "delete" item
            SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getApplicationContext());
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            // set item width
            deleteItem.setWidth(SizeUtils.dp2px(FavoriteActivity.this, 90));
            // set a icon
            deleteItem.setIcon(R.drawable.ic_delete);
            // add to menu
            menu.addMenuItem(deleteItem);
        }
    };

    private void cancelFav(final int position) {
        ArticleBean articleDetailBean = articleBeanList.get(position);
        HttpParams params = new HttpParams();
        params.put("uid", BaseApp.getModel().getId());
        params.put("id", articleDetailBean.getId());
        params.put("met", "no");
        String cacheKey = "bmark&uid=" + BaseApp.getModel().getId() + "id=" + articleDetailBean.getId();
        OkGoRequest.post(UrlUtils.BMARK, FavoriteActivity.this, cacheKey, CacheMode.NO_CACHE, params, new LoadingStringCallBack(FavoriteActivity.this,true) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                ToastUtils.show(context, "取消收藏");
                if (articleBeanList != null||articleBeanList.size()>0) {
                    articleBeanList.remove(position);
                    zhuanTiAdapter.notifyDataSetChanged();
                }
                if(articleBeanList == null||articleBeanList.size()==0)
                    rl_progress.setVisibility(View.VISIBLE);
                    findViewById(R.id.ll_no).setVisibility(View.VISIBLE);
                    avi.setVisibility(View.GONE);
                    ll_reload.setVisibility(View.GONE);
            }
        });
    }
}
